<template>
  <div class="app-container">
    <div class="search-bar">
      <el-form ref="queryFormRef" :model="queryParams" :inline="true">
        <el-form-item label="机构名称" prop="orgName">
          <el-input v-model="queryParams.orgName" placeholder="机构名称" clearable @keyup.enter="handleQuery()" />
        </el-form-item>
        <el-form-item label="机构地址" prop="address">
          <el-input v-model="queryParams.address" placeholder="机构地址" clearable @keyup.enter="handleQuery()" />
        </el-form-item>
        <el-form-item label="联系方式" prop="contact">
          <el-input v-model="queryParams.contact" placeholder="联系方式" clearable @keyup.enter="handleQuery()" />
        </el-form-item>
        <el-form-item label="审核状态" prop="status">
          <el-select v-model="queryParams.status" class="!w-[100px]" clearable placeholder="全部">
            <el-option :value="0" label="待审核" />
            <el-option :value="1" label="已认证" />
            <el-option :value="2" label="已注销" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">
            <template #icon>
              <Search />
            </template>
            搜索
          </el-button>
          <el-button @click="handleResetQuery">
            <template #icon>
              <Refresh />
            </template>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="never">
      <div class="mb-10px">
        <el-button v-hasPerm="['sys:org:add']" type="success" @click="handleOpenDialog()">
          <template #icon>
            <Plus />
          </template>
          新增
        </el-button>
        <el-button v-hasPerm="['sys:org:delete']" type="danger" :disabled="removeIds.length === 0"
          @click="handleDelete()">
          <template #icon>
            <Delete />
          </template>
          删除
        </el-button>
      </div>

      <el-table ref="dataTableRef" v-loading="loading" :data="pageData" highlight-current-row border
        @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column key="orgName" label="机构名称" prop="orgName" min-width="150" align="center" />
        <el-table-column key="username" label="所属用户" prop="username" min-width="150" align="center" />
        <el-table-column key="address" label="机构地址" prop="address" min-width="150" align="center" />
        <el-table-column key="contact" label="联系方式" prop="contact" min-width="150" align="center" />
        <el-table-column key="certification" label="资质证明文件" prop="certification" min-width="150" align="center">
          <template #default="scope">
            <el-link type="primary" :href="scope.row.certification" target="_blank">{{
              scope.row.certification }}</el-link>
          </template>
        </el-table-column>
        <el-table-column label="审核状态" width="150" align="center">
          <template #default="scope">
            <el-tag v-if="scope.row.status == 0" type="warning">待审核</el-tag>
            <el-tag v-if="scope.row.status == 1" type="success">已认证</el-tag>
            <el-tag v-if="scope.row.status == 2" type="info">已注销</el-tag>
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" width="220">
          <template #default="scope">
            <el-button v-hasPerm="['sys:org:edit']" type="primary" size="small" link
              @click="handleOpenDialog(scope.row.id)">
              <template #icon>
                <Edit />
              </template>
              编辑
            </el-button>
            <el-button v-hasPerm="['sys:org:delete']" type="danger" size="small" link
              @click="handleDelete(scope.row.id)">
              <template #icon>
                <Delete />
              </template>
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-if="total > 0" v-model:total="total" v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize" @pagination="handleQuery()" />
    </el-card>

    <!-- 机构管理表单弹窗 -->
    <el-dialog v-model="dialog.visible" :title="dialog.title" width="500px" @close="handleCloseDialog">
      <el-form ref="dataFormRef" :model="formData" :rules="rules" label-width="100px">
        <el-form-item label="机构名称" prop="orgName">
          <el-input v-model="formData.orgName" placeholder="机构名称" />
        </el-form-item>
        <el-form-item label="所属用户" prop="username">
          <el-select style="margin-right: 5px" v-model="formData.userId" class="!w-[100px]" placeholder="请选择">
            <el-option v-for="item in orgUserOptions" :value="item.userId" :label="item.username"></el-option>
          </el-select>
          <el-tooltip effect="dark" content="原用户将重置为普通用户" placement="top-start">
            <el-icon color="#575757FF">
              <QuestionFilled />
            </el-icon>
          </el-tooltip>
        </el-form-item>
        <el-form-item label="机构地址" prop="address">
          <el-input v-model="formData.address" placeholder="机构地址" />
        </el-form-item>

        <el-form-item label="联系方式" prop="contact">
          <el-input v-model="formData.contact" placeholder="联系方式" />
        </el-form-item>

        <el-form-item label="资质证明文件" prop="certification">
          <FileUpload v-model="formData.certification" :isEdit="true" :limit="1"></FileUpload>

        </el-form-item>

        <!--超管可以编辑状态，用来确认审核-->
        <el-form-item v-if="userStore.judgeAdminUser()" label="审核状态" prop="status">
          <el-select v-model="formData.status" class="!w-[100px]" placeholder="请选择">
            <el-option :value="0" label="待审核"></el-option>
            <el-option :value="1" label="已认证"></el-option>
            <el-option :value="2" label="已注销"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleSubmit()">确定</el-button>
          <el-button @click="handleCloseDialog()">取消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { QuestionFilled } from "@element-plus/icons-vue";
defineOptions({
  name: "Org",
  inheritAttrs: false,
});

import OrgAPI, { OrgPageVO, OrgForm, OrgPageQuery } from "@/api/system/org";
import { useUserStore } from "@/store";
import FileUpload from "@/components/Upload/FileUpload.vue";

const userStore = useUserStore();
const queryFormRef = ref();
const dataFormRef = ref();

const loading = ref(false);
const removeIds = ref<number[]>([]);
const total = ref(0);

const queryParams = reactive<OrgPageQuery>({
  pageNum: 1,
  pageSize: 10,
});

// 机构管理表格数据
const pageData = ref<OrgPageVO[]>([]);

// 弹窗
const dialog = reactive({
  title: "",
  visible: false,
});

// 机构管理表单数据
const formData = reactive<OrgForm>({});


// 机构管理表单校验规则
const rules = reactive({
  id: [{ required: true, message: "请输入机构表主键", trigger: "blur" }],
});

/** 查询机构管理 */
function handleQuery() {
  loading.value = true;
  OrgAPI.getPage(queryParams)
    .then((data) => {
      pageData.value = data.list;
      total.value = data.total;
    })
    .finally(() => {
      loading.value = false;
    });
}

/** 重置机构管理查询 */
function handleResetQuery() {
  queryFormRef.value!.resetFields();
  queryParams.pageNum = 1;
  handleQuery();
}

/** 行复选框选中记录选中ID集合 */
function handleSelectionChange(selection: any) {
  removeIds.value = selection.map((item: any) => item.id);
}

/** 打开机构管理弹窗 */
//机构可指定用户列表
const orgUserOptions = ref();
const oldUserId = ref(); //机构隶属的原userId

async function handleOpenDialog(id?: number) {
  dialog.visible = true;
  if (id) {
    orgUserOptions.value = await OrgAPI.getWorkersByOrgId(id?.toString());
    dialog.title = "修改机构管理";
    OrgAPI.getFormData(id).then((data) => {
      Object.assign(formData, data);
      oldUserId.value = formData.userId;
      orgUserOptions.value.push({ userId: formData.userId, username: formData.username });
    });
  } else {
    orgUserOptions.value = await OrgAPI.getAllWorkers();
    dialog.title = "新增机构管理";
  }
}
/** 提交机构管理表单 */
async function handleSubmit() {
  dataFormRef.value.validate((valid: any) => {
    if (valid) {
      loading.value = true;
      const id = formData.id;
      if (id) {
        formData.oldUserId = oldUserId.value;
        OrgAPI.update(id, formData)
          .then(() => {
            ElMessage.success("修改成功");
            handleCloseDialog();
            handleResetQuery();
          })
          .finally(() => (loading.value = false));
      } else {
        OrgAPI.add(formData)
          .then(() => {
            ElMessage.success("新增成功");
            handleCloseDialog();
            handleResetQuery();
          })
          .finally(() => (loading.value = false));
      }
    }
  });
}

/** 关闭机构管理弹窗 */
function handleCloseDialog() {
  dialog.visible = false;
  dataFormRef.value.resetFields();
  dataFormRef.value.clearValidate();
  formData.id = undefined;
  formData.userId = "";
  oldUserId.value = "";
}

/** 删除机构管理 */
function handleDelete(id?: number) {
  const ids = [id || removeIds.value].join(",");
  if (!ids) {
    ElMessage.warning("请勾选删除项");
    return;
  }

  ElMessageBox.confirm("确认删除已选中的数据项?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(
    () => {
      loading.value = true;
      OrgAPI.deleteByIds(ids)
        .then(() => {
          ElMessage.success("删除成功");
          handleResetQuery();
        })
        .finally(() => (loading.value = false));
    },
    () => {
      ElMessage.info("已取消删除");
    }
  );
}

onMounted(() => {
  handleQuery();
});
</script>
